package com.common.config.orm;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(
        basePackages = {"com.ck.**.dao", "com.ck.**.mapper"},
        sqlSessionFactoryRef = CkDataSourceConfig.ClickHouseSqlSessionFactory
)
public class CkDataSourceConfig {

    public static final String ClickHouseDataSource = "clickHouseDataSource";
    public static final String ClickHouseSqlSessionFactory = "clickHouseSqlSessionFactory";
    public static final String ClickHouseSqlSessionTemplate = "clickHouseSqlSessionTemplate";
    public static final String ClickHouseTransactionManager = "clickHouseTransactionManager";
    public static final String ClickHouseMapperLocations = "classpath*:mapper/clickhouse/**/*.xml";

    @Bean(name = ClickHouseDataSource)
    @ConfigurationProperties(prefix = "spring.datasource.clickhouse")
    public DataSource clickHouseDataSource() {
        // 手动创建 DruidDataSource，不使用 DruidDataSourceBuilder
        return new DruidDataSource();
    }


    @Bean(name = ClickHouseSqlSessionFactory)
    public SqlSessionFactory clickHouseSqlSessionFactory(
            @Qualifier(ClickHouseDataSource) DataSource dataSource,
            @Qualifier("clickHousePlusInterceptor") MybatisPlusInterceptor clickHousePlusInterceptor,
            @Qualifier("globalConfig") GlobalConfig globalConfig
    ) throws Exception {
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(dataSource);


        // 扫描 Mapper.xml 文件
        mybatisSqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(ClickHouseMapperLocations));

        // 注入 MyBatis-Plus 拦截器（分页等功能生效的核心）
        mybatisSqlSessionFactoryBean.setPlugins(clickHousePlusInterceptor);

        // 设置全局配置
        mybatisSqlSessionFactoryBean.setGlobalConfig(globalConfig);

        // 自定义 MyBatis 基础配置（保留不变）
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class); // 控制台日志打印
        configuration.setMapUnderscoreToCamelCase(true); // 驼峰映射命名
        configuration.setCacheEnabled(false); // 禁用二级缓存
        // 一级缓存作用域，默认为 SESSION，现在设为 STATEMENT
        // 因为一级缓存可能间接的会导致，数据实时性差，影响数据的一致性
        configuration.setLocalCacheScope(LocalCacheScope.STATEMENT);
        mybatisSqlSessionFactoryBean.setConfiguration(configuration);

        return mybatisSqlSessionFactoryBean.getObject();
    }

    @Bean(name = ClickHouseTransactionManager)
    public DataSourceTransactionManager clickHouseTransactionManager(
            @Qualifier(ClickHouseDataSource) DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = ClickHouseSqlSessionTemplate)
    public SqlSessionTemplate clickHouseSqlSessionTemplate(
            @Qualifier(ClickHouseSqlSessionFactory) SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}